<template>
  <!-- <span class="title">Customer List</span> -->
  <div class="condition">
    <el-form :model="searchForm">
      <el-row :gutter="20" class="flex_start">
        <el-col :span="2"><span class="label">{{ t(`module.table.Keywords`) }}</span></el-col>
        <el-col :span="10">
          <el-input v-model="searchForm.keyword" :placeholder="`${t('module.table.Name')}/${t('module.table.Email')}`">
            <template #append>
              <el-button :icon="Search" @click="searchFunc"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="10" style="float: right; margin-top:17px;">
          <el-button type="primary" @click="addCustomer">{{ t(`module.table.AddAccountForm`) }}</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <div class="datatable">
    <el-table :data="result.list" border style="width: 100%; box-sizing: border-box">
      <el-table-column prop="email" :label="t(`module.table.Email`)" :align="'center'" width="180" />
      <el-table-column prop="real_name" :label="t(`module.table.Name`)" :align="'center'" width="120" />
      <el-table-column prop="mobile" :label="t(`module.table.Tel`)" :align="'center'" width="180" />
      <el-table-column prop="area_name" :label="t(`module.table.Area`)" :align="'center'" width="220" />
      <el-table-column prop="created_at" :label="t(`module.table.CreateTime`)" :align="'center'" width="200" />
      <el-table-column prop="is_freeze" :label="t(`module.table.Active`)" width="100" :align="'center'">
        <template #default="scope">
          <el-switch v-model="scope.row.is_freeze" class="ml-2" style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            " :active-value="0" :inactive-value="1" @change="changeUserStatus($event, scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="remark" :label="t(`module.table.Remark`)" width="200" :align="'center'" />
      <el-table-column :label="t(`module.table.Handle`)" width="200" :align="'center'">
        <template #default="scope">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-button @click="edit(scope.row)">{{ t(`module.table.Edit`) }}</el-button>
            </el-col>
            <el-col :span="10">
              <el-popconfirm @confirm="del(scope.row.account_id)" title="Are you sure to delete this account?">
                <template #reference>
                  <el-button type="warning">{{ t(`module.table.Delete`) }}</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <el-row :gutter="20" class="mt_20">
      <el-col :span="10" :offset="10">
        <el-pagination small background layout="prev, pager, next" :total="result.total" class="mt-4"
                       @current-change="changePage" :current-page="searchForm.page">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
  <bind-dialog :showDialog="dialogBindVisible" :selectedUserId="selectedUserId" @closeDialog="closeDialog">
  </bind-dialog>

  <!-- 新增编辑弹窗 -->
  <el-dialog center :close-on-click-modal="false" v-model="dialogFormVisible" :title="form.action == 'edit' ? t(`module.table.EditAccountForm`) : t(`module.table.AddAccountForm`)">
    <el-form :model="form" label-width="120px" label-position="left" style="max-width: 70%">
      <el-form-item class="is-required" :label="t(`module.table.Email`)" :label-width="formLabelWidth">
        <el-input :placeholder="t(`module.table.DefaultInputEmail`)" v-model="form.email" autocomplete="off" />
      </el-form-item>
      <el-form-item class="is-required" :label="t(`module.table.Password`)" :label-width="formLabelWidth">
        <el-input :placeholder="t(`module.table.DefaultInputPassword`)" v-model="form.password_text" autocomplete="off" />
      </el-form-item>
      <el-form-item class="is-required" :label="t(`module.table.FullName`)" :label-width="formLabelWidth">
        <el-input :placeholder="t(`module.table.DefaultInputFirstName`)" v-model="form.first_name" autocomplete="off" />
        <el-input style="margin-top:1rem" :placeholder="t(`module.table.DefaultInputLastName`)" v-model="form.last_name" autocomplete="off" />
      </el-form-item>
      <el-form-item class="is-required" :label="t(`module.table.Role`)" :label-width="formLabelWidth">
        <el-select :placeholder="t(`module.table.DefaultSelectRole`)" v-model="form.role_id" check-strictly>
          <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item class="is-required" :label="t(`module.table.Project`)" :label-width="formLabelWidth">
        <el-tree-select :placeholder="t(`module.table.DefaultSelectTopLevel`)" v-model="form.organization_id"  @change="selectProject" :data="organizationList" :render-after-expand="false"
                        check-strictly />
      </el-form-item>
      <el-form-item class="is-required" :label="t(`module.table.Area`)" :label-width="formLabelWidth">
        <el-tree-select :placeholder="t(`module.table.DefaultSelectSubLevel`)" v-model="form.area_id" :data="areaList" :render-after-expand="false" check-strictly />
      </el-form-item>
      <el-form-item :label="t(`module.table.Zone`)" :label-width="formLabelWidth">
        <el-tree-select
          :placeholder="t(`module.table.DefaultSelectZone`)"
          v-model="form.zone"
          :data="zoneList"
          :render-after-expand="false"
          check-strictly
        />
      </el-form-item>
      <el-form-item :label="t(`module.table.Remark`)" :label-width="formLabelWidth">
        <el-input :placeholder="t(`module.table.DefaultInputRemark`)" type="textarea" v-model="form.remark" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">{{ t(`module.table.Cancel`) }}</el-button>
        <el-button type="primary" @click="submit">{{ t(`module.table.Confirm`) }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { onMounted, reactive, toRefs } from "vue";
import { useI18n } from "vue-i18n";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
// import BindDialog from "@/components/Device/bind.vue";
import MD5 from "md5";
import API from "api";

export default {
  name: "Account-List",
  components: {
    // BindDialog,
  },
  setup() {
    const { t } = useI18n();

    let state = reactive({
      result: {
        list: [],
        total: 0,
      },
      searchForm: {
        page: 1,
        keyword: "",
      },
      form: {
        id: 0,
        action: "",
        username: "",
        real_name: "",
        first_name: "",
        last_name: "",
        email: "",
        password: "",
        password_text: "",
        mobile: "",
        area_id: "",
        department_id: 0,
        job_id: 0 ,
        remark: "",
        role_id: "",
        zone: "",
      },
      selectedUserId: 0,
      selectedDevice: [],
      currentStatus: true,
      dialogBindVisible: false,
      dialogFormVisible: false,
      roleList: [],
      tenantList: [],
      organizationList: [],
      communityList: [],
      sectionList: [],
      areaList: [],
      departmentList: [],
      jobList: [],
      zoneList: [],
      deviceList: [],
      devicePage: 1,
    });
    onMounted(() => {
      getUserList();
    });
    const searchFunc = () => {
      // 搜索重置为第一页
      state.searchForm.page = 1;
      getUserList();
    };
    const getUserList = () => {
      API.userList({
        page: state.searchForm.page,
        keyword: state.searchForm.keyword,
      }).then((res) => {
        if (res.code == 0) {
          state.result = res.data;
        }
      });
    };
    const initList = (organizationId = 0) => {
      // initDepartmentList();
      initAreaList(organizationId);
      // initJobList();
      initOrganizationList();
      initZoneList();
      initRoleList();
    };
    const addCustomer = () => {
      initList();
      state.dialogFormVisible = true;
    };
    const edit = (param) => {
      state.form = param;
      initList(param.organization_id);
      state.dialogFormVisible = true;
    };
    const bind = (param) => {
      initDeviceList();
      state.selectedUserId = param.account_id;
      state.dialogBindVisible = true;
    };
    const closeDialog = () => {
      state.dialogBindVisible = false;
    };
    const del = (id) => {
      API.handleUser({ account_id: id, action: "delete" }).then((res) => {
        if (res.code == 0) {
          ElMessage({
            message: t(`module.table.Success`),
            type: "success",
            duration: 3000,
          });
        }
      });
    };
    const submit = () => {
      state.form.action = "edit";
      if (state.form.account_id == 0 || state.form.account_id == null) {
        state.form.action = "add";
        state.form.id = null;
      }
      if (state.form.action == 'add' && state.form.password_text < 8) {
        ElMessage.error("passwords should be 8 or more characters in length.");
        return;
      }
      if (state.form.email == "" || state.form.email.indexOf('@') < 1) {
        ElMessage.error("please enter a valid email address.");
        return;
      }
      if (state.form.first_name == "") {
        ElMessage.error("please enter your first name.");
        return;
      }
      if (state.form.last_name == "") {
        ElMessage.error("please enter your first name.");
        return;
      }
      if (state.form.email == "" || state.form.email.indexOf('@') < 1) {
        ElMessage.error("please enter a valid email address.");
        return;
      }
      if (state.form.area_id == "") {
        ElMessage.error("please choose a sublevel.");
        return;
      }
      if (state.form.organization_id == "") {
        ElMessage.error("please choose a top level.");
        return;
      }
      if (state.form.role_id == "") {
        ElMessage.error("you have to choose a role for this account.");
        return;
      }
      if (state.form.password_text && state.form.password_text != "") {
        state.form.password = MD5(state.form.password_text);
      }
      state.form.area_id = parseInt(state.form.area_id);
      state.form.organization_id = parseInt(state.form.organization_id);
      state.form.role_id = parseInt(state.form.role_id);
      API.handleUser(state.form).then((res) => {
        if (res.code != 0) {
          ElMessage.error(res.msg);
          return;
        }
        initForm();
        state.dialogFormVisible = false;
        ElMessage({
          message: "Success",
          type: "success",
          duration: 3000,
        });
        getUserList()
      });
    };

    const cancel = () => {
      initForm();
      state.dialogFormVisible = false;
    };

    const initForm = () => {
      state.form = {
        username: "",
        real_name: "",
        first_name: "",
        last_name: "",
        email: "",
        password: "",
        password_text: "",
        mobile: "",
        role_id: "",
        remark: "",
        area_id: "",
        zone: "",
      };
    };
    const initRoleList = () => {
      API.roleList({ page: 0 }).then((res) => {
        state.roleList = res.data.list;
        console.log(state.roleList);
      });
    };
    const initDeviceList = () => {
      API.deviceList({ page: state.devicePage }).then((res) => {
        state.deviceList = res.data.list;
      });
    };
    // 获取小区列表
    const initAreaList = (organizationId = 0) => {
      let param = { type: "area" }
      if (organizationId != 0) {
        param.organization_id = organizationId
      }
      API.settingList(param).then((res) => {
        state.areaList = res.data;
      });
    };
    // 获取部门列表
    const initDepartmentList = () => {
      API.settingList({ type: "department" }).then((res) => {
        state.departmentList = res.data;
      });
    };
    // 获取岗位列表
    const initJobList = () => {
      API.settingList({ type: "job" }).then((res) => {
        state.jobList = res.data;
      });
    };
    // 获取组织列表
    const initOrganizationList = () => {
      API.organizationList().then((res) => {
        state.organizationList = res.data;
      });
    };
    // 获取时区列表
    const initZoneList = () => {
      API.zoneList().then((res) => {
        state.zoneList = res.data;
      });
    };
    const changePage = (page) => {
      state.searchForm.page = page;
      getUserList();
    };

    const changeUserStatus = (val, row) => {
      let action = "";
      let showText = "";
      if (val == 1) {
        // 禁用
        action = "freeze";
        showText = "freeze successed";
      } else {
        action = "active";
        showText = "active successed";
      }

      API.handleUser({ account_id: row.account_id, action: action }).then(
        (res) => {
          if (res.code == 0) {
            ElMessage({
              message: showText,
              type: "success",
              duration: 3000,
            });
          }
        }
      );
      // if (row.is_deleted == 0) {
      //   // active
      //   // API.handleUser()
      // } else {
      //   // disabled
      // }
    };
    const selectProject = (organizationId) => {
      state.form.area_id = ''
      initAreaList(organizationId)
    }
    return {
      t,
      searchFunc,
      changePage,
      addCustomer,
      edit,
      ...toRefs(state),
      submit,
      cancel,
      changeUserStatus,
      del,
      bind,
      closeDialog,
      selectProject,
      Search,
    };
  },
};
</script>

<style lang="scss" scoped>
.condition {
  margin-top: 4vh;

  .label {
    padding: 0 10px;
  }
}

.title {
  display: block;
  padding: 2rem 1rem;
  font-size: 2rem;
  font-weight: bolder;
  text-align: left;
}

.search {
  display: flex;
  width: 30rem;
  padding: 1rem;
}

.datatable {
  box-sizing: border-box;
  padding: 0.625rem;
}

.ml-1 {
  margin-left: 1rem;
}
</style>
